package com.sww.pj.sys.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.sww.pj.common.annotation.RequiredLog;
import com.sww.pj.common.exception.ServiceException;
import com.sww.pj.common.pojo.Node;
import com.sww.pj.common.utils.ShiroUtils;
import com.sww.pj.sys.dao.RoleMenuDao;
import com.sww.pj.sys.dao.SysMenuDao;
import com.sww.pj.sys.dao.SysUserRoleDao;
import com.sww.pj.sys.pojo.SysMenu;
import com.sww.pj.sys.pojo.SysUser;
import com.sww.pj.sys.pojo.SysUserMenu;
import com.sww.pj.sys.service.SysMenuService;
@Service
public class SysMenuServiceImpl implements SysMenuService {

	@Autowired
	private SysMenuDao sysMenuDao;
	@Autowired
	private RoleMenuDao roleMenuDao;

	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	
	
	
	public List<SysUserMenu> findUserMenus(Integer userId) {
		List<Integer> roleIds=sysUserRoleDao.findRoleIdsByUserId(userId);
		List<Integer> menuIds=roleMenuDao.findMenuIdsByRoleIds(roleIds);
		return sysMenuDao.findUserMenus(menuIds);
	}
	

	@Override
	@RequiresPermissions("sww:menu:find")
	@RequiredLog("查询菜单")
	public List<Map<String, Object>> findObjects() {
		List<Map<String, Object>> list=sysMenuDao.findObjects();
		if(list==null||list.size()==0)
			throw new ServiceException("没有对应的菜单信息");
		return list;
	}
	@Override
	@RequiresPermissions("sww:menu:delete")
	@RequiredLog("删除菜单")
	public int deleteObject(Integer id) {
		//1.验证数据的合法性
		if(id==null||id<=0)
			throw new IllegalArgumentException("请先选择");
		//2.基于id进行子元素查询
		int count=sysMenuDao.getChildCount(id);
		if(count>0)
			throw new ServiceException("请先删除子菜单");
		//3.删除角色,菜单关系数据
		roleMenuDao.deleteObjectsByMenuId(id);
		//4.删除菜单元素
		int rows=sysMenuDao.deleteObject(id);
		if(rows==0)
			throw new ServiceException("此菜单可能已经不存在");
		//5.返回结果
		return rows;
	}
	@Override
	public List<Node> findZtreeMenuNodes() {
		return sysMenuDao.findZtreeMenuNodes();
	}
	@Override
	@RequiresPermissions("sww:menu:add")
	@RequiredLog("添加菜单")
	public int saveObject(SysMenu entity) {
		//1.合法验证
		if(entity==null)
			throw new IllegalArgumentException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getName()))
			throw new IllegalArgumentException("菜单名不能为空");
		//2.保存数据
		int  rows=sysMenuDao.insertObject(entity);
		//3.返回数据
		return rows;
	}
	@Override
	@RequiresPermissions("sww:menu:update")
	@RequiredLog("修改菜单")
	public int updateObject(SysMenu entity) {
		//1.合法验证
		if(entity==null)
			throw new ServiceException("保存对象不能为空");
		if(StringUtils.isEmpty(entity.getName()))
			throw new ServiceException("菜单名不能为空");	               
		//2.更新数据
		int rows=sysMenuDao.updateObject(entity);
		if(rows==0)
			throw new ServiceException("记录可能已经不存在");
		//3.返回数据
		return rows;
	}
}
